package cn.tedu._05mvcboot.controller;

import cn.tedu._05mvcboot.common.response.JsonResult;
import cn.tedu._05mvcboot.mapper.Mapper;
import cn.tedu._05mvcboot.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot.pojo.entyti.Article;
import cn.tedu._05mvcboot.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot.pojo.vo.UserVO;
import cn.tedu._05mvcboot.common.response.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "01.用户模块")
@Validated
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private Mapper mapper;
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult select(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        log.debug("userLoginDTO="+userLoginDTO);
        //获取用户名、密码
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //校验用户名、密码
        UserVO userVO = mapper.select(username, password);
        if (userVO!=null){//登录成功
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
    @ApiOperation(value = "发表文章功能")
    @PostMapping("article")
    private JsonResult insert(@RequestBody UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO==null){//未登录
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        mapper.insert(article);
        return JsonResult.ok();
    }
    @ApiOperation(value = "查询指定文章功能")
    @ApiImplicitParam(name="id",value = "文章ID",required = true,dataType = "Long")
    @GetMapping("selectByArticleId")
    public JsonResult selectById(@Range(min = 1,max = 100,message = "文章ID必须在1到100之间") Long id){
        ArticleVO articleVO = mapper.selectById(id);
        return JsonResult.ok(articleVO);
    }
}
